/*
 *  Copyright (C) 2010 Zubanov Dmitry
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 *
 * @author Zubanov Dmitry aka javadimon, zubanov@gmail.com
 * Omsk, Russia, created 21.09.2010
 * (C) Copyright by Zubanov Dmitry
 */
package org.jssdb.core.net;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

public class DataChunkList {

    /**
     * pack object to DataChunk array list
     * @param obj
     * @return
     * @throws Exception
     */
    public ArrayList<DataChunk> getDataChunkList(Object obj) throws IOException{
        ArrayList<DataChunk> dataChunkList = new ArrayList();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oout = new ObjectOutputStream(baos);
        oout.writeObject(obj);
        oout.flush();
        oout.close();

        byte[] bData = baos.toByteArray();
        if (bData.length < DataChunkSize.getInstance().getSize()) {
            DataChunk dataChunk = new DataChunk(new Date().getTime(), 1, 1, obj.getClass(), bData);
            dataChunkList.add(dataChunk);

        } else {
            long id = new Date().getTime();
            int count = bData.length / DataChunkSize.getInstance().getSize();
            long partCount = count + 1;
            int end = 0;
            for (int i = 0; i < count; i++) {
                int start = i * DataChunkSize.getInstance().getSize();
                end = start + DataChunkSize.getInstance().getSize();
                byte bDataChunk[] = Arrays.copyOfRange(bData, start, end);
                DataChunk dataChunk = new DataChunk(id, i + 1, partCount, obj.getClass(), bDataChunk);
                dataChunkList.add(dataChunk);
            }

            byte bDataChunk[] = Arrays.copyOfRange(bData, end, bData.length);
            DataChunk dataChunk = new DataChunk(id, partCount, partCount, obj.getClass(), bDataChunk);
            dataChunkList.add(dataChunk);
        }

        return dataChunkList;
    }
}
